import React, { useState, useEffect, useRef } from 'react';
import {
  Row,
  Col,
  Card,
  Space,
  Button,
  Popover,
  Popconfirm,
  InputNumber,
  Input,
  message,
} from 'antd';
import Icon, {
  ZoomOutOutlined,
  ZoomInOutlined,
  CloseOutlined,
  EyeOutlined,
  PrinterOutlined,
  DiffOutlined,
} from '@ant-design/icons';

import { hiprint } from '@/index';
import providers from './providers';
import printData from './print-data';
import panel from './panel';
import { useIntl } from 'umi';
import ChildComp from './components/preview';
import './index.less';
import { useLocation, useParams } from 'umi';
import { getDesignFileDetailById } from '@/services/systemUtil/printDesignItem';
import { updatePrintDesignFile, updateFileContent } from '@/services/systemUtil/printDesignFile';
// let hiprintTemplate: any;
const Login: React.FC = () => {
  const intl = useIntl();
  const hiprintTemplate = useRef();
  const childRef = useRef();

  // 当前纸张
  const [curPaper, handleCurPaper] = useState<object>({
    type: 'A4',
    width: 210,
    height: 296.6,
  });
  // 纸张类型
  const paperTypes = {
    A3: {
      width: 420,
      height: 296.6,
    },
    A4: {
      width: 210,
      height: 296.6,
    },
    A5: {
      width: 210,
      height: 147.6,
    },
    B3: {
      width: 500,
      height: 352.6,
    },
    B4: {
      width: 250,
      height: 352.6,
    },
    B5: {
      width: 250,
      height: 175.6,
    },
  };
  const [scaleValue, handleScaleValue] = useState<number>(1);
  const [scaleMax] = useState<number>(5);
  const [scaleMin] = useState<number>(0.5);
  // 自定义纸张
  const [paperPopVisible, handlePaperPopVisible] = useState<boolean>(false);
  const [paperWidth, handlePaperWidth] = useState<number>(210);
  const [paperHeight, handlePaperHeight] = useState<number>(296.6);
  const location = useLocation();
  const provider = providers[0];
  console.log(location.query.id, '---ceshi1---');
  useEffect(() => {
    (async () => {
      // 相当于新建
      if (location.query.id !== undefined && location.query.id !== null) {
        const result = await getDesignFileDetailById(location.query.id);
        //初始化页面
        const fileContext = {
          panels: [
            {
              index: 0,
              paperType: 'A4',
              height: 297,
              width: 210,
              paperHeader: 43.5,
              paperFooter: 841,
              printElements: [],
              paperNumberLeft: 565,
              paperNumberTop: 819,
            },
          ],
        };
        console.log(result, '---result---');
        const _customPrintJson = JSON.parse(result.data.fileContext)
          ? JSON.parse(result.data.fileContext)
          : fileContext;

        const fields = result.data.items;

        console.log(result, '---result---');
        $(document).ready(function () {
          hiprint.init({
            providers: [provider.f],
          });
          $('#hiprintEpContainer').empty();

          hiprint.PrintElementTypeManager.build('#hiprintEpContainer', provider.value);
          $('#hiprint-printTemplate').empty();
          hiprintTemplate.current = new hiprint.PrintTemplate({
            template: _customPrintJson,
            settingContainer: '#PrintElementOptionSetting',
            paginationContainer: '.hiprint-printPagination',
          });
          hiprintTemplate.current.design('#hiprint-printTemplate');
          // 初始化时判断纸张类型
          if (_customPrintJson.panels[0].height && _customPrintJson.panels[0].width) {
            for (const key in paperTypes) {
              if (
                paperTypes[key].height == _customPrintJson.panels[0].height &&
                paperTypes[key].width == _customPrintJson.panels[0].width
              ) {
                setPaper(key, {
                  width: _customPrintJson.panels[0].width,
                  _customPrintJson: panel.panels[0].height,
                });
                break;
              } else {
                setPaper('other', {
                  width: _customPrintJson.panels[0].width,
                  height: _customPrintJson.panels[0].height,
                });
              }
            }
          }
          hiprintTemplate.current.setFields(fields);
          // 获取当前放大比例, 当zoom时传true 才会有
          handleScaleValue(hiprintTemplate.current.editingPanel.scale || 1);
        });

        console.log('hiprint====>');
      }
    })();
  }, []);
  // 自定义纸张大小
  function otherPaper() {
    const PaperValue: Object = {
      width: 0,
      height: 0,
    };
    PaperValue['width'] = paperWidth;
    PaperValue['height'] = paperHeight;
    handlePaperPopVisible(false);
    setPaper('other', PaperValue);
  }
  function handleVisibleChange(visible: boolean) {
    handlePaperPopVisible(visible);
  }
  // 缩放
  function changeScale(val: boolean) {
    let scaleValues = scaleValue;
    if (val) {
      scaleValues += 0.1;
      if (scaleValue > scaleMax) scaleValues = 5;
    } else {
      scaleValues -= 0.1;
      if (scaleValue < scaleMin) scaleValues = 0.5;
    }
    if (hiprintTemplate.current) {
      // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
      hiprintTemplate.current.zoom(scaleValues, false);
      handleScaleValue(scaleValues);
    }
  }
  // 预览
  function preView() {
    childRef?.current?.show(hiprintTemplate.current, printData, curPaper['width']);
  }
  // 打印
  // function print() {
  //   if (window?.hiwebSocket?.opened) {
  //     const printerList = hiprintTemplate.current.getPrinterList();
  //     hiprintTemplate.current.print2(printData, {
  //       printer: '',
  //       title: 'hiprint测试打印',
  //     });
  //     return;
  //   }
  //   const defaultLoginSuccessMessage = intl.formatMessage({
  //     id: 'pages.operation',
  //     defaultMessage: '客户端未连接,无法直接打印',
  //   });
  //   message.error(defaultLoginSuccessMessage);
  // }
  // 保存
  async function save() {
    await updateFileContent({
      id: location.query.id,
      fileContext: JSON.stringify(hiprintTemplate.current.getJson()),
    });
    message.info('保存成功');
    // setTemplate({
    //   name: provider.value,
    //   json: hiprintTemplate.current.getJson(),
    // });
  }
  function setTemplate(payload: any) {
    console.log(payload.json);
    const defaultLoginSuccessMessage = intl.formatMessage({
      id: 'pages.saveSuccess',
      defaultMessage: '保存成功',
    });
    message.success(defaultLoginSuccessMessage);
  }
  // 清空设计
  function clearPaper() {
    try {
      hiprintTemplate.current.clear();
    } catch (error) {
      const defaultLoginSuccessMessage = intl.formatMessage({
        id: 'pages.operation',
        defaultMessage: '操作失败',
      });
      message.error(defaultLoginSuccessMessage);
    }
  }
  // 是否初次渲染
  const isInit = useRef(true);
  // 监听纸张变化
  useEffect(() => {
    if (isInit.current) {
      isInit.current = false;
    } else {
      hiprintTemplate.current.setPaper(curPaper['width'], curPaper['height']);
    }
  }, [curPaper]);

  // 设置纸张
  function setPaper(type: string, value: object) {
    try {
      if (Object.keys(paperTypes).includes(type)) {
        handleCurPaper({
          type: type,
          width: paperTypes[type].width,
          height: paperTypes[type].height,
        });
        handlePaperWidth(paperTypes[type].width);
        handlePaperHeight(paperTypes[type].height);
        // hiprintTemplate.setPaper(paperTypes[type].width, paperTypes[type].height);
      } else {
        handleCurPaper({
          type: 'other',
          width: value['width'],
          height: value['height'],
        });
        handlePaperWidth(value['width']);
        handlePaperHeight(value['height']);
        // hiprintTemplate.setPaper(value['width'], value['height']);
      }
    } catch (error) {
      const defaultLoginSuccessMessage = intl.formatMessage({
        id: 'pages.operation',
        defaultMessage: '操作失败',
      });
      message.error(defaultLoginSuccessMessage);
    }
  }
  // 鼠标拖拽事件
  function draggableFun(e: any, value: string) {
    const div = document.getElementById(value);
    let xLeft: number, xRight: number;
    // div.onmousedown = (e) => {
    if (e.button === 0) {
      //鼠标左键按下事件
      e = e || window.event;
      xLeft = e.clientX - div.offsetLeft; //鼠标在元素上距离元素左边的距离
      xRight = div.offsetWidth - xLeft; //鼠标在元素上距离元素右边的距离

      // 鼠标移动
      document.onmousemove = function ($e) {
        $e = $e || window.event;
        const left: number = $e.clientX - xLeft;
        const FWidth: number = $e.clientX + xRight; //元素最右边
        const a = document.getElementsByTagName('main');
        // 判断当前元素左右可以活动的区域
        if (left <= 0) {
          div.style.left = 0 + 'px';
        } else if (FWidth >= a[0].offsetWidth) {
          div.style.right = 0 + 'px';
        } else if (left > 0) {
          div.style.left = left + 'px';
        }
      };
      // 鼠标抬起事件
      document.onmouseup = function (e) {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    }
  }

  return (
    <div style={{ position: 'relative', height: '100%' }}>
      <Row gutter={[8, 0]}>
        <Col>
          <Space>
            {/* 纸张设置 */}
            <Button.Group>
              {Object.keys(paperTypes).map((key) => {
                return (
                  <Button
                    key={key}
                    onClick={() => {
                      setPaper(key, paperTypes[key]);
                    }}
                    type={curPaper['type'] == key ? 'primary' : 'default'}
                  >
                    {key}
                  </Button>
                );
              })}
              <Popover
                trigger="click"
                visible={paperPopVisible}
                onVisibleChange={handleVisibleChange}
                title="设置纸张宽高(mm)"
                content={
                  <div>
                    <Input.Group compact style={{ margin: '10px 10px' }}>
                      <Input
                        type="number"
                        value={paperWidth}
                        onChange={(e) => {
                          handlePaperWidth(Number(e.target.value));
                        }}
                        style={{ width: '100px', textAlign: 'center' }}
                        placeholder="宽(mm)"
                      />
                      <Input
                        style={{
                          width: '30px',
                          borderLeft: '0',
                          pointerEvents: 'none',
                          backgroundColor: '#fff',
                        }}
                        placeholder="~"
                        disabled
                      />
                      <Input
                        type="number"
                        value={paperHeight}
                        onChange={(e) => {
                          handlePaperHeight(Number(e.target.value));
                        }}
                        style={{ width: '100px', textAlign: 'center', borderLeft: '0' }}
                        placeholder="高(mm)"
                      />
                    </Input.Group>
                    <Button
                      type="primary"
                      style={{ width: '100%}' }}
                      onClick={() => {
                        otherPaper();
                      }}
                    >
                      确定
                    </Button>
                  </div>
                }
              >
                <Button type={curPaper['type'] == 'other' ? 'primary' : 'default'}>
                  自定义纸张
                </Button>
              </Popover>
            </Button.Group>
            {/* 缩放 */}

            <Button
              icon={<ZoomOutOutlined />}
              onClick={() => {
                changeScale(false);
              }}
            />
            <InputNumber
              style={{ width: '70px' }}
              disabled
              value={scaleValue}
              min={scaleMin}
              max={scaleMax}
              step="0.1"
              formatter={(value) => `${(value * 100).toFixed(0)}%`}
              parser={(value) => value.replace('%', '')}
            />
            <Button
              icon={<ZoomInOutlined />}
              onClick={() => {
                changeScale(true);
              }}
            />
            <Button.Group>
              <Button
                type="primary"
                icon={<EyeOutlined />}
                onClick={() => {
                  preView();
                }}
              >
                预览
              </Button>
              {/* <Button
                type="primary"
                onClick={() => {
                  print();
                }}
              >
                直接打印
                <PrinterOutlined />
              </Button> */}
            </Button.Group>
            <Button.Group>
              <Button
                type="primary"
                icon={<DiffOutlined />}
                onClick={() => {
                  save();
                }}
              >
                保存
              </Button>
              <Popconfirm
                title="是否确认清空?"
                okType="danger"
                okText="确定清空"
                onConfirm={clearPaper}
              >
                <Icon slot="icon" type="question-circle-o" style={{ color: 'red' }} />
                <Button type="primary" danger>
                  清空
                  <CloseOutlined />
                </Button>
              </Popconfirm>
            </Button.Group>
          </Space>
        </Col>
      </Row>
      <Row
        gutter={[8, 0]}
        style={{ position: 'relative', height: 'calc(100% - 40px)', margin: '0' }}
      >
        <Col
          span={5}
          id="cardLeft"
          // style={{
          //   position: 'absolute',
          //   zIndex: '999',
          //   // top: '20px',
          //   overflow: 'auto',
          //   height: '100%',
          //   // width: '17%',
          //   marginTop: '20px',
          // }}
        >
          {/* <div
            onMouseDown={(e) => {
              draggableFun(e, 'cardLeft');
            }}
            style={{
              height: '500px',
              borderBottom: '0',
              cursor: 'move',
              backgroundColor: '#fa742b',
            }}
          /> */}
          <Card style={{ borderTop: '0', height: 'calc(100% - 24px)', overflow: 'auto' }}>
            <Row>
              <Col className="rect-printElement-types" id="hiprintEpContainer" />
            </Row>
          </Card>
        </Col>
        {/* <div style={{ position: 'relative', width: '100%', height: '100%' }}> */}
        <Col
          span={14}
          style={{
            position: 'absolute',
            // top: '20px',
            overflow: 'auto',
            height: '100%',
            marginLeft: '20.8%',
            marginTop: '20px',
          }}
        >
          <Card className="cardDesign">
            <div
              id="hiprint-printTemplate"
              className="hiprint-printTemplate"
              style={{ paddingTop: '24px' }}
            />
          </Card>
        </Col>
        {/* </div> */}
        <Col
          span={5}
          className="params_setting_container"
          id="back"
          style={{
            position: 'absolute',
            height: '100%',
            overflow: 'auto',
            right: '0',
            // zIndex: '999',
            // top: '40px',
            width: '100%',
            marginTop: '20px',
          }}
        >
          <div
            onMouseDown={($event) => {
              draggableFun($event, 'back');
            }}
            style={{
              height: '24px',
              borderBottom: '0',
              cursor: 'move',
              backgroundColor: '#fa742b',
            }}
          />
          <Card style={{ borderTop: '0', height: 'calc(100% - 24px)', overflow: 'auto' }}>
            <Row className="hinnn-layout-sider">
              <div id="PrintElementOptionSetting" />
            </Row>
          </Card>
        </Col>
      </Row>
      <ChildComp ref={childRef} />
    </div>
  );
};

export default Login;
